import { api } from "@/api";
import { request } from "@/lib";
import { ApiCode } from "@/types/api/base";
import { MyLoginParam } from "@/types/api/my";
import { My } from "@/types/service/my";

export const useMyStore = defineStore('my', {
    state: () => {
        return {
            accessToken: uni.getStorageSync('accessToken') ?? '',
            info: {} as My,
            pid: '',
        }
    },
    getters: {
        /**是登录 */
        isLogin: (state) => !!state.accessToken,
    },
    actions: {
        //#ifdef MP
        /**小程序登录 */
        async login(data: MyLoginParam<'mp'>) {
            const res = await request.post<{ token: string }>(api.login, data)
            if (res.code !== ApiCode.success) return Promise.reject(res.msg)
            this.accessToken = res.data.token
            uni.setStorageSync('accessToken', this.accessToken)
            return Promise.resolve(res.data)
        },
        //#endif
        //#ifdef H5
        /**H5登录 */
        async loginH5(data: MyLoginParam<'h5'>) {
            const res = await request.post<{ token: string }>(api.login, data)
            if (res.code !== ApiCode.success) return Promise.reject(res.msg)
            this.accessToken = res.data.token
            return Promise.resolve(res.data)
        },
        //#endif
        /**获取信息 */
        async getInfo() {
            const res = await request.get<any>(api.my.getInfo)
            if (res.code !== ApiCode.success) return Promise.reject(res.msg)
            this.info = res.data.info
            return Promise.resolve(res.data)
        }
    },
    persist: {
        enabled: true,
        strategies: [{
            paths: ['accessToken', 'pid']
        }]
    }
})